package com.robot.mannge.common.config.security.handler;

import com.alibaba.fastjson2.JSON;
import com.robot.mannge.auth.domain.vo.SysUserVO;
import com.robot.mannge.common.result.BaseResult;
import com.robot.mannge.common.result.ResultCode;
import com.robot.mannge.common.utils.jwt.JwtUtils;
import com.robot.mannge.common.utils.jwt.LoginResult;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: Smile
 * @Date: 2024/01/30/11:52
 * @Description:
 */

/**
 * 登录认证成功处理类
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //设置响应的编码格式
        response.setContentType("application/json;charset=utf-8");
        //获取当前登录用户的信息
        SysUserVO principal = (SysUserVO) authentication.getPrincipal();
        //生成token
        String token = jwtUtils.createToken(principal);
        //设置过期时间
        Long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())//设置签名密钥
                .parseClaimsJws(token.replace("jwt_",""))
                .getBody().getExpiration().getTime();//获取过期时间
        //创建登录结果对象
        LoginResult loginResult = new LoginResult(principal.getId(),
                ResultCode.SUCCESS.code(), token, expireTime);


        //将对象转换成json
        String jsonString = JSON.toJSONString(BaseResult.success(loginResult));//loginResult
        //输出到流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
